<template>
  <div>
    <div id="map-container">
    <div id="map-controls" style="position: absolute; top: 10px; left: 10px; z-index: 1000;">
      <select v-model="selectedDay" @change="filterByDay">
         <option value="all">所有天数</option>
         <option v-for="day in availableDays" :value="day">第{{ day }}天</option>
       </select>
    </div>
    <div id="map"></div>
  </div>
    <div class="upload-container">
      <input 
        type="file" 
        accept=".csv,.xlsx,.xls,.json" 
        @change="handleFileUpload"
        style="margin-top: 20px; padding: 10px;"
      >
      <p>上传旅游攻略文件(支持CSV/Excel/JSON格式)</p>
    </div>
  </div>
</template>

<script>
export default {
  name: 'TravelMap',
  data() {
    return {
      AMapKey: '2bf97a17fd73a34f046a82230abd1db1',
      map: null,
      markers: [],
      polylines: [],
      routes: [],
      selectedRoute: null,
      selectedDay: 'all',
      availableDays: []
    }
  },
  async mounted() {
    await this.$nextTick();
    await this.initAMap();
    await this.fetchRoutes();
  },
  beforeUnmount() {
    // 清理地图实例
    if (this.map) {
      this.map.destroy();
      this.map = null;
    }
    this.clearMarkers();
  },
  methods: {
    async handleFileUpload(event) {
      const file = event.target.files[0];
      if (!file) return;
      
      const formData = new FormData();
      formData.append('file', file);
      
      try {
        const response = await fetch('http://localhost:5000/upload', {
          method: 'POST',
          body: formData
        });
        
        if (!response.ok) {
          throw new Error(`上传失败: ${response.statusText}`);
        }
        
        const result = await response.json();
        if (result.error) {
          throw new Error(result.error);
        }
        
        // 处理返回的活动和通勤数据
        if (result.activities && result.activities.length > 0) {
          this.clearMarkers();
          
          // 设置路由数据
          this.setSelectedRoute(result);
          
          // 处理活动数据
          result.activities.forEach(activity => {
            if (activity.location && activity.location.coordinates) {
              this.addMarker(
                [activity.location.coordinates.longitude, activity.location.coordinates.latitude], 
                activity.title || '活动', 
                {
                  name: activity.location.name,
                  time: activity.time_slot,
                  order_index: activity.order_index || activity.day_number * 100 + (activity.order_index || 0),
                  address: activity.location.address,
                  type: activity.type,
                  fee: activity.details.cost,
                  reservation: activity.details.reservation_required ? '需要' : '无需',
                  title: activity.title,
                  date: activity.date,
                  day_number: activity.day_number
                }
              );
            }
          });
          
          // 处理通勤数据
          // 提取所有天数
          const days = new Set();
          if (result.activities) {
            result.activities.forEach(activity => {
              if (activity.day_number) days.add(activity.day_number);
            });
          }
          if (result.transports) {
            result.transports.forEach(transport => {
              if (transport.day_number) days.add(transport.day_number);
            });
          }
          this.availableDays = Array.from(days).sort((a, b) => a - b);
          this.selectedDay = 'all';
          
          if (result.transports && result.transports.length > 0) {
            const transportPoints = [];
            
            // 收集通勤起点和终点
            result.transports.forEach(transport => {
              if (!transport.location || !transport.location.from || !transport.location.from.coordinates || 
                  !transport.location.to || !transport.location.to.coordinates) {
                console.warn('通勤数据不完整:', transport);
                return;
              }
              
              transportPoints.push({
                lng: transport.location.from.coordinates.longitude,
                lat: transport.location.from.coordinates.latitude,
                name: transport.location.from.name
              });
              
              transportPoints.push({
                lng: transport.location.to.coordinates.longitude,
                lat: transport.location.to.coordinates.latitude,
                name: transport.location.to.name
              });
              
              // 绘制路线
              this.drawRoute(transportPoints, transport);
            });
          }
        }
      } catch (error) {
        console.error('文件上传失败:', error);
      }
    },
    
    async fetchRoutes() {
      try {
        const response = await fetch('http://localhost:5000/routes');
        this.routes = await response.json();
        console.log('线路数据加载成功:', this.routes);
        
        // 默认显示第一条线路
        if (this.routes.length > 0) {
          this.selectRoute(this.routes[0]);
        }else{
          console.log('没有可用的线路数据');
        }
      } catch (error) {
        console.error('获取线路数据失败:', error);
      }
    },
    
    setSelectedRoute(routeData) {
      if (!routeData || (!routeData.activities && !routeData.transports)) {
        console.error('无效的线路数据:', routeData);
        return;
      }
      this.selectedRoute = routeData;
      this.selectRoute(routeData);
    },
    
    addMarker(position, title = '', pointData = {}) {
      if (!this.map) return;
      
      const marker = new AMap.Marker({
        position: position,
        title: title,
        map: this.map,
        label: {
          content: pointData.order_index ? pointData.order_index.toString() : '无',
          offset: new AMap.Pixel(20, 20)
        }
      });
      
      // 添加鼠标悬停事件
      let markerInfoWindow = null;
      marker.on('mouseover', () => {
        markerInfoWindow = new AMap.InfoWindow({
          content: `<div style="padding:5px;min-width:200px">
            <div style="font-size:16px;font-weight:bold;margin-bottom:5px">${pointData.name || title || '景点'}</div>
            <div><strong>序号:</strong> ${pointData.order_index || '无'}</div>
            <div><strong>时间:</strong> ${pointData.time || '无'}</div>
            <div><strong>地址:</strong> ${pointData.address || '无'}</div>
            <div><strong>类型:</strong> ${pointData.type || '无'}</div>
            <div><strong>费用:</strong> ${pointData.fee || 0}元</div>
            <div><strong>预约:</strong> ${pointData.reservation || '无需'}</div>
            <div style="margin-top:5px"><small>经度: ${position[0].toFixed(4)}</small></div>
            <div><small>纬度: ${position[1].toFixed(4)}</small></div>
          </div>`,
          offset: new AMap.Pixel(0, -30)
        });
        markerInfoWindow.open(this.map, position);
      });
      
      // 添加鼠标离开事件
      marker.on('mouseout', () => {
        if (markerInfoWindow) {
          markerInfoWindow.close();
        }
      });
      
      this.markers.push(marker);
      return marker;
    },
    
    clearMarkers() {
      this.markers.forEach(marker => {
        marker.setMap(null);
      });
      this.markers = [];
      
      this.polylines.forEach(polyline => {
        polyline.setMap(null);
      });
      this.polylines = [];
    },
    
    drawRoute(points, transport) {
      console.log('绘制路线:', points);
      // 过滤无效坐标点
      const validPoints = points.filter(point => point && point.lng && point.lat);
      if (validPoints.length < 2) {
        console.log('有效坐标点不足，无法绘制路线:', validPoints);
        return;
      }
      
      const path = validPoints.map(point => [point.lng, point.lat]);
      
      const polyline = new AMap.Polyline({
        path: path,
        isOutline: true,
        outlineColor: '#ffeeff',
        borderWeight: 1,
        strokeColor: '#3366FF',
        strokeOpacity: 1,
        strokeWeight: 6,  // 增加线宽
        strokeStyle: 'solid',
        lineJoin: 'round',
        lineCap: 'arrow',
        showDir: true,    // 显示方向箭头
        // dirColor: '#FF0000',  // 箭头颜色
        dirSize: 1,      // 增加箭头大小
        // dirImg: './image.png',  // 使用完整URL路径引用图片
        zIndex: 50,
        map: this.map
      });
      
      // 添加鼠标悬停事件显示通勤信息
      let polylineInfoWindow = null;
      polyline.on('mouseover', (e) => {
        if (!transport) {
          console.warn('缺少transport参数');
          return;
        }
        
        polylineInfoWindow = new AMap.InfoWindow({
          content: `<div style="padding:5px;min-width:250px">
            <div style="font-size:16px;font-weight:bold;margin-bottom:5px">${transport.title}</div>
            <div><strong>行程ID:</strong> ${transport.trip_id}</div>
            <div><strong>日期:</strong> ${transport.date}</div>
            <div><strong>时间段:</strong> ${transport.time_slot}</div>
            <div><strong>交通方式:</strong> ${transport.transport.mode}</div>
            <div><strong>距离:</strong> ${transport.transport.distance_km}公里</div>
            <div><strong>时长:</strong> ${transport.transport.duration_minutes}分钟</div>
            <div><strong>费用:</strong> ${transport.transport.cost}元</div>
            <div><strong>起点:</strong> ${transport.location.from.name}</div>
            <div><strong>终点:</strong> ${transport.location.to.name}</div>
          </div>`,
          offset: new AMap.Pixel(0, -30)
        });
        
        // 在鼠标位置显示信息窗口
        polylineInfoWindow.open(this.map, [e.lnglat.getLng(), e.lnglat.getLat()]);
      });
      
      // 添加鼠标离开事件
      polyline.on('mouseout', () => {
        if (polylineInfoWindow) {
          polylineInfoWindow.close();
        }
      });
      
      // 自动调整视图到路线范围
      if (polyline) {
        this.polylines.push(polyline);
        this.map.setFitView([polyline]);
      }
      return polyline;
    },
    
    selectRoute(route) {
      if (!route || (!route.activities && !route.transports)) {
        console.error('无效的线路数据:', route);
        return;
      }
      
      this.selectedRoute = route;
      this.clearMarkers();
      
      // 提取所有天数
      const days = new Set();
      if (route.activities) {
        route.activities.forEach(activity => {
          if (activity.day_number) days.add(activity.day_number);
        });
      }
      if (route.transports) {
        route.transports.forEach(transport => {
          if (transport.day_number) days.add(transport.day_number);
        });
      }
      this.availableDays = Array.from(days).sort((a, b) => a - b);
      this.selectedDay = 'all';
      
      this.filterByDay();
      
      // 添加活动标记点
      if (route.activities) {
        route.activities.forEach(activity => {
          if (activity.location && activity.location.coordinates) {
            this.addMarker(
              [activity.location.coordinates.longitude, activity.location.coordinates.latitude], 
              activity.title || '活动', 
              {
                name: activity.location.name,
                time: activity.time_slot,
                order_index: activity.order_index || activity.day_number * 100 + (activity.order_index || 0),
                address: activity.location.address,
                type: activity.type,
                fee: activity.details.cost,
                reservation: activity.details.reservation_required ? '需要' : '无需',
                title: activity.title,
                date: activity.date,
                day_number: activity.day_number
              }
            );
          }
        });
      }
      
      // 处理通勤数据
      if (route.transports) {
        // 绘制每条通勤路线
        route.transports.forEach(transport => {
          if (!transport.location.from || !transport.location.from.coordinates || 
              !transport.location.to || !transport.location.to.coordinates) {
            console.warn('通勤数据不完整:', transport);
            return;
          }
          
          const points = [
            {
              lng: transport.location.from.coordinates.longitude,
              lat: transport.location.from.coordinates.latitude,
              name: transport.location.from.name
            },
            {
              lng: transport.location.to.coordinates.longitude,
              lat: transport.location.to.coordinates.latitude,
              name: transport.location.to.name
            }
          ];
          this.drawRoute(points, transport);
        });
      }
    },
    
    async loadAMap() {
      try {
        console.log('开始加载@amap/amap-jsapi-loader模块...');
        const { default: AMapLoader } = await import('@amap/amap-jsapi-loader');
        console.log('模块加载成功:', AMapLoader);
        
        if (!AMapLoader || !AMapLoader.load) {
          throw new Error('AMapLoader未正确导入');
        }
        
        return await AMapLoader.load({
          key: this.AMapKey,
          version: '2.0',
          plugins: ['AMap.ToolBar', 'AMap.Scale', 'AMap.Marker', 'AMap.Polyline'],
          AMapUI: {
            version: '1.1',
            plugins: []
          }
        });
      } catch (e) {
        console.error('npm包加载失败:', e);
        console.log('回退到CDN加载方式');
        
        return new Promise((resolve, reject) => {
          // 检查是否已经加载
          if (window.AMap) {
            resolve(window.AMap);
            return;
          }
          
          const script = document.createElement('script');
          script.src = `https://webapi.amap.com/maps?v=2.0&key=${this.AMapKey}&plugin=AMap.ToolBar,AMap.Scale,AMap.Marker,AMap.Polyline`;
          script.crossOrigin = 'anonymous';
          script.onload = () => {
            console.log('CDN加载成功');
            resolve(window.AMap);
          };
          script.onerror = (err) => {
            console.error('CDN加载失败:', err);
            reject(new Error('高德地图加载失败'));
          };
          document.head.appendChild(script);
        });
      }
    },
    
    filterByDay() {
      console.log('当前选择的天数:', this.selectedDay);
      console.log('当前路由数据:', this.selectedRoute);
      if (!this.selectedRoute) return;
      
      this.clearMarkers();
      
      // 过滤活动数据
      if (this.selectedRoute.activities) {
        this.selectedRoute.activities.forEach(activity => {
          if (this.selectedDay === 'all' || activity.day_number === this.selectedDay) {
            if (activity.location && activity.location.coordinates) {
              this.addMarker(
                [activity.location.coordinates.longitude, activity.location.coordinates.latitude], 
                activity.title || '活动', 
                {
                  name: activity.location.name,
                  time: activity.time_slot,
                  order_index: activity.order_index || activity.day_number * 100 + (activity.order_index || 0),
                  address: activity.location.address,
                  type: activity.type,
                  fee: activity.details.cost,
                  reservation: activity.details.reservation_required ? '需要' : '无需',
                  title: activity.title,
                  date: activity.date,
                  day_number: activity.day_number
                }
              );
            }
          }
        });
      }
      
      // 过滤通勤数据
      if (this.selectedRoute.transports) {
        this.selectedRoute.transports.forEach(transport => {
          if (this.selectedDay === 'all' || transport.day_number === this.selectedDay) {
            if (!transport || !transport.location || !transport.location.from || !transport.location.from.coordinates || 
                !transport.location.to || !transport.location.to.coordinates) {
              console.warn('通勤数据不完整:', transport);
              return;
            }
              const points = [
                {
                  lng: transport.location.from.coordinates.longitude,
                  lat: transport.location.from.coordinates.latitude,
                  name: transport.location.from.name
                },
                {
                  lng: transport.location.to.coordinates.longitude,
                  lat: transport.location.to.coordinates.latitude,
                  name: transport.location.to.name
                }
              ];
              this.drawRoute(points, transport);
            }
        });
      }
    },
    
    async initAMap() {
      try {
        const AMap = await this.loadAMap();
        console.log('AMap对象加载完成:', AMap);
        
        this.map = new AMap.Map('map-container', {
          zoom: 10,
          center: [116.397428, 39.90923], // 北京
          viewMode: '2D'
        });
        
        console.log('地图实例创建成功');
        
        // 添加控件
        this.map.addControl(new AMap.ToolBar());
        this.map.addControl(new AMap.Scale());
        
        // 地图加载完成后重绘
        this.map.on('complete', () => {
          console.log('地图加载完成');
          this.map.resize();
        });
        
        // 确保地图正确显示
        setTimeout(() => {
          this.map && this.map.resize();
        }, 100);
        
      } catch (error) {
        console.error('地图初始化失败:', error);
        console.error('错误详情:', {
          message: error.message,
          stack: error.stack
        });
      }
    }
  }
}
</script>

<style scoped>
#map-container {
  width: 1600px;
  /* height: 100%; */
  min-height: 850px;
  border: 1px solid #ccc;
  background: #f0f0f0;
}

.upload-container {
  margin-top: 20px;
  padding: 15px;
  border: 1px dashed #ccc;
  text-align: center;
}
</style>